<template>
  <div class="chat-view">
    <div class="chat-messages" ref="messagesRef">
      <div v-if="messages.length === 0" class="empty-state">
        <Icon icon="mdi:robot" class="robot-icon" />
        <h2>开始一个新的对话</h2>
        <p>你可以问我任何问题</p>
      </div>
      
      <template v-else>
        <div 
          v-for="message in messages" 
          :key="message.id"
          class="message"
          :class="message.role"
        >
          <div class="message-avatar">
            <Icon 
              :icon="message.role === 'user' ? 'mdi:account' : 'mdi:robot'" 
              class="avatar-icon"
            />
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div v-if="message.role === 'assistant'" class="message-actions">
              <button class="action-btn" @click="copyMessage(message.content)" title="复制">
                <Icon icon="mdi:content-copy" />
              </button>
            </div>
          </div>
        </div>
      </template>

      <div v-if="isTyping" class="message assistant typing">
        <div class="message-avatar">
          <Icon icon="mdi:robot" class="avatar-icon" />
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-input">
      <form @submit.prevent="sendMessage" class="input-form">
        <div class="input-wrapper">
          <textarea
            v-model="inputMessage"
            @keydown.enter.prevent="handleEnter"
            placeholder="输入消息..."
            rows="1"
            ref="inputRef"
          ></textarea>
          <button 
            type="button" 
            class="clear-btn"
            v-if="inputMessage"
            @click="inputMessage = ''"
          >
            <Icon icon="mdi:close" />
          </button>
        </div>
        <button 
          type="submit" 
          class="send-btn"
          :disabled="!inputMessage.trim() || isTyping"
        >
          <Icon :icon="isTyping ? 'mdi:loading' : 'mdi:send'" />
        </button>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch, computed } from 'vue'
import { Icon } from '@iconify/vue'
import 'highlight.js/styles/github-dark.css'
import { useChatStore } from '@/stores/chat'
import { useRoute } from 'vue-router'
import { message } from '@/services/message'

const route = useRoute()
const chatStore = useChatStore()
const messages = computed(() => chatStore.currentSession?.messages || [])
const inputMessage = ref('')
// 使用计算属性从chatStore获取isLoading状态
const isTyping = computed(() => chatStore.isLoading)
const messagesRef = ref<HTMLElement | null>(null)
const inputRef = ref<HTMLTextAreaElement | null>(null)



// 格式化消息内容
const formatMessage = (content: string) => {
  if (!content) return ''
  // 使用pre标签保持格式
  return `<pre>${content}</pre>`
}

// 自动调整输入框高度
const adjustTextareaHeight = () => {
  if (inputRef.value) {
    inputRef.value.style.height = 'auto'
    inputRef.value.style.height = `${inputRef.value.scrollHeight}px`
  }
}

// 监听输入内容变化
watch(inputMessage, () => {
  nextTick(adjustTextareaHeight)
})

// 处理回车发送
const handleEnter = (e: KeyboardEvent) => {
  if (!e.shiftKey) {
    sendMessage()
  }
}

// 复制消息内容
const copyMessage = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
    // TODO: 显示复制成功提示
  } catch (err) {
    console.error('Failed to copy:', err)
  }
}

// 发送消息
const sendMessage = async () => {
  const message = inputMessage.value.trim()
  if (!message || chatStore.isLoading) return

  inputMessage.value = ''
  adjustTextareaHeight()

  try {
    await chatStore.sendMessage(message, (chunk) => {
      // 渲染新接收的文本块并滚动到底部
      const formattedChunk = formatMessage(chunk)
      // 更新DOM以显示格式化后的文本块
      if (messagesRef.value) {
        const lastMessage = messagesRef.value.querySelector('.message:last-child .message-text')
        if (lastMessage) {
          lastMessage.innerHTML = formattedChunk
        }
      }
      nextTick(() => {
        scrollToBottom()
      })
    })
  } catch (error) {
    alert('发送消息失败，请重试')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 监听路由参数变化
watch(() => route.params.id, async (newId) => {
  if (newId && typeof newId === 'string') {
    try {
      // 设置当前会话ID
      chatStore.currentSessionId = newId
      // 只有当不是新会话时才加载历史记录
      if (chatStore.currentSession?.messages.length === 0) {
        await chatStore.loadHistory(newId)
      }
    } catch (error) {
      console.error('Failed to load chat history:', error)
      message.error('加载历史记录失败')
    }
  } else {
    // 如果没有 ID 参数，清空当前会话
    chatStore.currentSessionId = null
  }
}, { immediate: true })

// 组件挂载时只加载会话列表
onMounted(async () => {
  try {
    await chatStore.loadSessions()
  } catch (error) {
    console.error('Failed to initialize chat view:', error)
    message.error('初始化失败，请刷新页面重试')
  }
})
</script>

<style lang="scss" scoped>
.chat-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-color, white);
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  background: linear-gradient(to bottom, rgba(250, 250, 250, 0.5), rgba(255, 255, 255, 0.8));
  
  .empty-state {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: var(--text-secondary, #666);
    padding: 20px;
    
    .robot-icon {
      font-size: 64px;
      margin-bottom: 24px;
      color: var(--primary-color, #42b883);
      animation: float 3s ease-in-out infinite;
      filter: drop-shadow(0 4px 6px rgba(66, 184, 131, 0.2));
    }
    
    h2 {
      font-size: 28px;
      margin-bottom: 12px;
      font-weight: 600;
      background: linear-gradient(135deg, var(--primary-color, #42b883), #2c9c6a);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
    }
    
    p {
      font-size: 16px;
      opacity: 0.8;
    }
  }
}

.message {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      background: var(--primary-light, rgba(66, 184, 131, 0.1));
      border-radius: 16px 4px 16px 16px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
  }
  
  &.assistant {
    .message-content {
      background: var(--message-bg, #f5f5f5);
      border-radius: 4px 16px 16px 16px;
      box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    }
  }
  
  .message-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background: var(--avatar-bg, #e0e0e0);
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);

    .avatar-icon {
      font-size: 24px;
      color: var(--text-secondary, #666);
    }
  }
  
  .message-content {
    flex: 0 1 auto;
    min-width: 100px;
    max-width: 80%;
    padding: 16px;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    transition: all 0.2s ease;
    
    :deep(.message-text) {
      flex: 1;
      line-height: 1.6;
      word-break: break-word;
      display: inline-block;
      font-size: 15px;
      
      // 移除所有元素的默认边距
      * {
        margin: 0;
        padding: 0;
      }
      
      // 只在需要的地方添加间距
      p + p,
      pre,
      ul,
      ol,
      blockquote {
        margin-top: 0.8em;
      }
      
      p {
        margin: 0 0 0.5em;
        
        &:last-child {
          margin-bottom: 0;
        }
      }
      
      pre {
        margin: 0.5em 0;
        padding: 14px;
        border-radius: 10px;
        background: rgba(0, 0, 0, 0.03);
        color: var(--text-color);
        overflow-x: auto;
        font-family: 'Fira Code', monospace;
        white-space: pre-wrap;
        word-wrap: break-word;
      }
      
      code {
        font-family: 'Fira Code', monospace;
        background: rgba(0, 0, 0, 0.05);
        padding: 2px 4px;
        border-radius: 4px;
        font-size: 0.9em;
      }
      
      ul, ol {
        margin: 0.5em 0;
        padding-left: 1.5em;
      }
      
      blockquote {
        margin: 0.8em 0;
        padding: 0.5em 1em;
        border-left: 4px solid var(--primary-color, #42b883);
        color: var(--text-secondary, #666);
        background: rgba(66, 184, 131, 0.05);
        border-radius: 0 4px 4px 0;
      }
      
      // 确保加粗文本正确显示
      strong, b {
        font-weight: bold;
      }
    }
    
    .message-actions {
      align-self: flex-end;
      margin-top: 10px;
      display: flex;
      opacity: 0;
      transition: opacity 0.3s ease;
      
      .action-btn {
        padding: 6px;
        border: none;
        background: rgba(0, 0, 0, 0.03);
        color: var(--text-secondary, #666);
        border-radius: 6px;
        display: flex;
        align-items: center;
        cursor: pointer;
        transition: all 0.2s ease;
        
        .iconify {
          font-size: 16px;
          transition: color 0.2s;
        }
        
        &:hover {
          background: rgba(66, 184, 131, 0.1);
          .iconify {
            color: var(--primary-color, #42b883);
          }
        }

        span {
          display: none;
        }
      }
    }
  }
  
  &:hover {
    .message-actions {
      opacity: 1;
    }
  }
  
  &.user .message-actions {
    justify-content: flex-end;
  }
}

.typing {
  .typing-indicator {
    display: flex;
    gap: 6px;
    padding: 8px;
    
    span {
      width: 10px;
      height: 10px;
      border-radius: 50%;
      background: var(--text-secondary, #666);
      animation: typing 1.2s infinite;
      opacity: 0.7;
      
      &:nth-child(2) {
        animation-delay: 0.2s;
      }
      
      &:nth-child(3) {
        animation-delay: 0.4s;
      }
    }
  }
}

.chat-input {
  padding: 20px;
  border-top: 1px solid var(--border-color, #e0e0e0);
  background: rgba(250, 250, 250, 0.8);
  backdrop-filter: blur(10px);
  
  .input-form {
    display: flex;
    gap: 12px;
    
    .input-wrapper {
      flex: 1;
      position: relative;
      
      textarea {
        width: 100%;
        padding: 14px 40px 14px 16px;
        border: 1px solid var(--border-color, #e0e0e0);
        border-radius: 12px;
        resize: none;
        max-height: 200px;
        font-family: inherit;
        font-size: 16px;
        line-height: 1.5;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        transition: all 0.3s ease;
        
        &:focus {
          outline: none;
          border-color: var(--primary-color, #42b883);
          box-shadow: 0 2px 12px rgba(66, 184, 131, 0.15);
        }
      }
      
      .clear-btn {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        background: none;
        border: none;
        color: var(--text-secondary, #666);
        cursor: pointer;
        padding: 4px;
        border-radius: 50%;
        
        &:hover {
          background: var(--hover-bg, rgba(0, 0, 0, 0.05));
        }
      }
    }
    
    .send-btn {
      width: 44px;
      height: 44px;
      border-radius: 12px;
      border: none;
      background: var(--primary-color, #42b883);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      box-shadow: 0 2px 6px rgba(66, 184, 131, 0.2);
      transition: all 0.3s ease;
      
      &:hover {
        background: var(--primary-hover, #3aa876);
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(66, 184, 131, 0.3);
      }
      
      &:disabled {
        opacity: 0.7;
        cursor: not-allowed;
      }
      
      .iconify {
        font-size: 20px;
      }
    }
  }
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
    opacity: 0.5;
  }
  50% {
    transform: translateY(-4px);
    opacity: 1;
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

@media (max-width: 768px) {
  .message {
    .message-content {
      max-width: 85%;
    }
  }
  
  .chat-input {
    padding: 15px;
    
    .input-form {
      .input-wrapper textarea {
        font-size: 15px;
      }
    }
  }
}
</style>